//
//  FPMainWebController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/13.
//

#import "FPMainWebController.h"
#import <WebKit/WebKit.h>

@interface FPMainWebController () <WKNavigationDelegate , WKUIDelegate>

@property (nonatomic , strong) WKWebView *webView;
@property (nonatomic , strong) UIActivityIndicatorView *loadingView;

@end

@implementation FPMainWebController

- (UIActivityIndicatorView *)loadingView {
    
    if (!_loadingView) {
    
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium];
        loadingView.hidesWhenStopped = YES;
        [self.view addSubview:_loadingView = loadingView];
//        loadingView.center = self.view.center;
        loadingView.frame = CGRectMake(SCREEN_WIDTH / 2.f - 37.f / 2.f, SCREEN_HEIGHT / 2.f - 37.f / 2.f, 37.f, 37.f);
    }
    return _loadingView;
}


- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
        
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr stopMonitoring];
    
    // 清缓存
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    if (self.userPanGestureInvalid) {
        
        [UIViewController popGestureClose:self];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.userPanGestureInvalid) {
     
        [UIViewController popGestureOpen:self];
    }
    
//    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

//- (void)backAction {
//    
//    if ([self.webView canGoBack]) {
//        
//        [self.webView goBack];
//        return;
//    }
//}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)initUI {
    
    /*    // web 自适应大小
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
        webConfig.userContentController = wkUController;
        self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webConfig];
    */
    
    self.webView = [[WKWebView alloc] init]; // 打开自适应 就要关掉这个alloc (重复了)
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    self.webView.frame = CGRectMake(0, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT-UIDevice.navigationFullHeight);
    
    [self.view addSubview:self.webView];
    
    [self.loadingView startAnimating];
    
    NSString *naviTitle;
    NSString *urlStr;
    
    NSString *baseURLString = @"https://api.xm.bkcredit.cn/xy/";
    
    switch (self.protocolType) {
            
        case FPProtocolTypeSettingUserProtocol:
            
            self.urlString = [baseURLString stringByAppendingString:@"RegistrationAgreement.html"];
//            self.titleString = @"用户服务协议";
            break;
            
        case FPProtocolTypeSettingPrivacyProtocol:
            
            self.urlString = [baseURLString stringByAppendingString:@"PrivacyPolicy.html"];
//            self.titleString = @"用户隐私保护政策";
            break;
            
        default:
            break;
    }
    
    if (self.urlString.length) {
        
        naviTitle = self.titleString;
        
        [self loadRequestWithTitle:naviTitle URLString:self.urlString];
        
        // 右上角 x
        /*
        [self setRightButton];
//        [self.rightBtn setTitle:@"X" forState:(UIControlStateNormal)];
//        [self.rightBtn setTitleColor:UIColor.blackColor forState:(UIControlStateNormal)];
        [self.rightBtn setBackgroundImage:IMG(@"icon_close_black") forState:(UIControlStateNormal)];
        [self.rightBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
           
            [self.navigationController popViewControllerAnimated:YES];
        }];
         */
    }
    else {
     
        // 协议类型的 web
        if (self.model) {
            
            [self getSignedProtocolInfo];
        }
        else {
            
            [self showText:@"无效的URL"];
            [self performSelector:@selector(backAction) withObject:nil afterDelay:1.5f];
            
//            naviTitle = @"title";
//            urlStr = @"https://www.baidu.com";
//            
//            [self loadRequestWithTitle:naviTitle URLString:urlStr];
        }
    }
    
//    self.urlString = urlStr;
//    self.titleStr = naviTitle;
}


#pragma mark - 查看已签署协议的信息
- (void)getSignedProtocolInfo {
    
    NSString *URLStr = [NSString stringWithFormat:@"%@?dataToken=%@", self.model.address , FPUserModel.globalToken];
    
    if (self.cooperateName.length > 0) {
        
        URLStr = [URLStr stringByAppendingFormat:@"&companyName=%@&cooperateName=%@" , self.companyName , self.cooperateName];
    }
    
    if (self.protocolType == FPProtocolTypeListController) {
        
        URLStr = [NSString stringWithFormat:@"%@", self.model.address];
    }
    
    [self loadRequestWithTitle:self.model.agreementName URLString:URLStr];
    
//    [FPProtocolModel getProtocolSignInfoWithID:self.model.ID success:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
//        [self.loadingView stopAnimating];
//        
//        if (code == 200) {
//            
//#warning 获取到协议信息 处理 URL
//            [self loadRequestWithTitle:self.model.agreementName URLString:self.model.address];
//        }
//        else {
//            
////            [self showText:message];
////            [self setTitle:@"访问出错" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
//            [self loadRequestWithTitle:self.model.agreementName URLString:self.model.address];
//        }
//        
//    } failure:^(NSError * _Nonnull error) {
//        [self.loadingView stopAnimating];
//        [self showError:error];
//    }];
}


- (void)loadRequestWithTitle:(NSString *)naviTitle URLString:(NSString *)URLString {
    
//    [self checkNetChange];
    
    [self setTitle:naviTitle style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    NSURLRequest *request = [NSURLRequest requestWithURL:[self exchangePercentURLString:URLString]];
    [self.webView loadRequest:request];
}

- (NSURL *)exchangePercentURLString:(NSString *)urlStr {
    
    NSMutableCharacterSet *set  = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [set addCharactersInString:@"#"];
    NSURL *URL = [NSURL URLWithString:[urlStr stringByAddingPercentEncodingWithAllowedCharacters:set]];
    
    return URL;
}

- (void)assynError {
    
    [self showText:@"未找到该页面"];
    [self.loadingView stopAnimating];
    [self performSelector:@selector(backAction) withObject:nil afterDelay:1.5f];
}


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
    
    if ([message.name isEqualToString:@"alipay"]) {
        
        [self showText:message.name];
    }
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        if (challenge.previousFailureCount == 0) {
            // 如果没有错误的情况下 创建一个凭证，并使用证书
            NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential , credential);
        } else {
            // 验证失败，取消本次验证
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *jpURL = navigationAction.request.URL.absoluteString;
    
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    
    if ([scheme isEqualToString:@"tel"]) {
        
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
        });
    }
    else {
        
        if ([jpURL hasPrefix:@"alipays://"] || [jpURL hasPrefix:@"alipay://"]) {
            
            // NOTE: 跳转支付宝App
//                BOOL bSucc = [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            BOOL bSucc = [[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL];
            
            // NOTE: 如果跳转失败，则跳转itune下载支付宝App
            if (!bSucc) {
                
                [MBManager showText:@"未安装支付宝"];
            }
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}


#pragma mark - 开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
//    [self.loadingView startAnimating];
}

#pragma mark - 网页加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
    
//    NSLog(@"网页标题: %@", webView.title);
//    [self setTitle:webView.title style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
//    [webView evaluateJavaScript:@"displayDate()" completionHandler:^(id _Nullable object, NSError * _Nullable error) {
//       
//        if (error) {
//            
////            [self showError:error];
//        }
//        else {
//            NSLog(@"%@",object);
//        }
//    }];
}

#pragma mark - 加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {

    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
}

#pragma mark - 导航失败
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
}

# pragma mark - 检测网络变化 用于埋点
- (void)checkNetChange {
    
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态发生改变的时候调用这个block
        switch (status) {
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                
//                [self showText:@"wifi"];
                // 埋点
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
//                [self showText:@"自带的 3G/4G/5G"];
                // 埋点
                break;

            case AFNetworkReachabilityStatusNotReachable:
                
                [self showText:@"无网络连接"];
//                [NSUserDefaults.standardUserDefaults setObject:@"without" forKey:@"network"];
                break;

            case AFNetworkReachabilityStatusUnknown:
                
//                [self showText:@"未知网络"];
                // 埋点
                break;
                
            default:
                
                break;
        }}];
    
    [mgr startMonitoring];
}



@end
